<template>
  <van-button
        size="small"
        type="primary"
        native-type="button"
        :disabled="!status"
        class="send"
        @click="start()"
        >{{ status ? content : remainSecondes }}</van-button
    >
</template>

<script>
export default {
    props: {
        content: {
            type: String,
            require: true
        },
        seconds: {
            type: Number,
            default: 60
        },
        // 验证的正则
        reg: {
            type: RegExp,
            default: /.*/, // 默认是通配符
        },
        // 待验证的字符串
        waitVerifyContext: {
            type: String
        }
    },
    data() {
        return {
            status: true, // 倒计时状态
            remainSecondes: this.seconds
        }
    },
    methods: {
        start() {
            // 告知使用者点击了倒计时按钮, 把使用者传进来的待验证字符串传回去
            this.$emit('sendSomething', this.waitVerifyContext);
            if(this.reg.test(this.waitVerifyContext)) {
                // 表示开始倒计时, 验证通过才倒计时
                this.status = false; 
                let timer = setInterval(() => {
                    this.remainSecondes--;
                    if(this.remainSecondes <= 0) {
                        this.status = true;
                        this.remainSecondes = this.seconds;
                        clearInterval(timer);
                    }
                }, 1000);
            }
        }
    }
}
</script>

<style scoped>
    .send {
        width: 60px;
        margin-left: 8px;
    }
</style>